<?php
/**
 * TomatoCMS
 *
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 *
 * @copyright    Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license        http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version     $Id: ProductController.php 3075 2010-05-26 15:41:59Z quanvo $
 */

class Shop_ProductController extends Zend_Controller_Action
{
	/**
	* Test List Products Of one Enterprise is active or deactive
	* (note) : chi dung` de test
	*
	*/
	public function testlistproductAction(){
		$front = Zend_Controller_Front::getInstance();
		$request = $front->getRequest();
		$params  = $request->getParams();
		$enterprise_id = $params["test_enterprise_id"];
		$this->view->enterprise_id = $enterprise_id;
	}
	
    /**
    * Add new product
    *
    * @return void
    */
    public function addAction(){
        $this->view->addHelperPath(TOMATO_APP_DIR . DS . 'modules' . DS . 'upload' . DS . 'views' . DS . 'helpers', 'Upload_View_Helper_');

        /**
         * Get current user
        **/
        $user = Zend_Auth::getInstance()->getIdentity();

        /**
         * Get current date
         **/
        $date = date('d/m/Y');
        $this->view->assign('date', $date);

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Category model access to data
        **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
        * Get all category to tree view
        **/
        $categories = $categoryDao->getCategoryTree();
        $this->view->assign('categories', $categories);

        /**
         * Product model access to data
         **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);

        /**
        * Enterprise model access to data
        **/
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Get relationship info between user and enterprise
         **/
        $userAccount = $userAccountDao->getByUser($user->user_id);

        /**
         * Check enterprise exist
         * @return: die if enterprise_id not exist
        **/
        /*if(!isset($userAccount->enterprise_id) && !@$userAccount->enterprise_id){
            die('Not found enterprise for user');
        }*/

        /**
         * Get enterprise info for product currency
         **/
        if($userAccount){
            $enterprise = $enterpriseDao->getById($userAccount->enterprise_id);
            $this->view->assign('enterprise', $enterprise);
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            /**
            * Handle category to string
            **/
            $arrCategoryId = $request->getPost('category_id');
            $strCategoryId = ",";
            foreach ($arrCategoryId as $row){
                $strCategoryId .= $row.',';
            }

            $product_admin_name         = $request->getPost('product_admin_name');
            $product_price              = $request->getPost('product_price');
            $product_price_currency     = isset($enterprise->currency)?$enterprise->currency:'USD';
            $product_status_of_delivery = $request->getPost('product_status_of_delivery');
            $product_quantity           = @$request->getPost('product_quantity');
            $product_quantity_mode      = @$request->getPost('product_quantity_mode');
            $product_status             = $request->getPost('product_status');
            $category_id                = $strCategoryId;
            $account_id                 = 1;//value to test
            $product_bundle             = $request->getPost('product_bundle');
            $product_product_id_chain   = $request->getPost('product_product_id_chain');
            $product_shipping_price     = $request->getPost('product_shipping_price');
            $product_image              = $request->getPost('product_image');
            $enterprise_id              = ($userAccount)?$userAccount->enterprise_id:null;
            $product_shipping_price_1   = $request->getPost('product_shipping_price_1');
            $product_shipping_price_2   = $request->getPost('product_shipping_price_2');

            $purifier = new HTMLPurifier();
            $product = new Shop_Models_Product(array(
                'product_admin_name'         => $purifier->purify($product_admin_name),
                'category_id'                => $category_id,
                'account_id'                 => $account_id,
                'product_price'              => $product_price,
                'product_price_currency'     => $product_price_currency,
                'product_status_of_delivery' => $product_status_of_delivery,
                'product_quantity'           => $product_quantity,
                'product_quantity_mode'      => $product_quantity_mode,
                'product_status'             => $product_status,
                'product_created_date'       => date('Y-m-d H:i:s'),
                'product_modified_date'      => date('Y-m-d H:i:s'),
                'product_bundle'             => $product_bundle,
                'product_product_id_chain'   => $product_product_id_chain,
                'product_shipping_price'     => $product_shipping_price,
                'product_image'              => $product_image,
                'enterprise_id'              => $enterprise_id,
                'product_shipping_price_1'   => $product_shipping_price_1,
                'product_shipping_price_2'   => $product_shipping_price_2,
            ));
            $id = $productDao->add($product);
            if ($id > 0) {
                $this->_helper->getHelper('FlashMessenger')->addMessage(
                    $this->view->translator('product_add_success')
                );
                $this->_redirect($this->view->serverUrl().$this->view->url(array('product_id' => $id), 'shop_product_edit'));
            }
        }
    }

    /**
    * List product
    *
    * @return void
    */
    public function listAction(){

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();		
		
        /**
         * Product model acess to data
         **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);

        /**
         * Product content access to data
         **/
        $productContentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductContentDao();
        $productContentDao->setDbConnection($conn);

        /**
         * Category model access to data
         **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
         * Get current user
         **/
        $user = Zend_Auth::getInstance()->getIdentity();

        /**
        * Get category information to tree view
        **/
        $categories = $categoryDao->getCategoryTree();
        $this->view->assign('categories', $categories);

        /**
         * Get relationship between current user and enterprise
         **/
        $userAccount = $userAccountDao->getByUser($user->user_id);

        $request    = $this->getRequest();
        $pageIndex  = $this->_request->getParam('pageIndex', 1);
        $perPage    = 20;
        $offset     = ($pageIndex - 1) * $perPage;
        $purifier     = new HTMLPurifier();

        /**
         * Build product search expression
         **/
        $params = null;
        $exp    = array();

        /**
        * Check permission all list enterprise
        */
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            $exp['enterprise_id'] = $purifier->purify(@$userAccount->enterprise_id);
        }

        if ($request->isPost()) {
            $categoryId   = $request->getPost('category');
            if ($categoryId) {
                $exp['category_id'] = $categoryId;
            }
            $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
        } else {
            $params = $request->getParam('q');
            if (null != $params) {
                $exp = rawurldecode(base64_decode($params));
                $exp = Zend_Json::decode($exp);
            } else {
                $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
            }
        }

        /**
        * Get list product and count all product to paginator
        * $offset: position start
        * $perPage: item pager
        * $exp: condition
        **/
        $products   = $productDao->find($offset, $perPage, $exp);
        $numProduct = $productDao->count($exp);

        /**
         * Get language content each product
         * $arrPoductContentName: to assign language information foreach match product
         **/
        $arrPoductContentName = array();
        foreach ($products as $row){
            $product_content = $productContentDao->getProductContentByProductId($row->product_id, "pc.language_code DESC");
            $strPoductContentName = '';
            $i = 0;
            foreach ($product_content as $row1){
                $strBr = null;
                if($i >= 1){
                    $strBr = "<br/>";
                }
                $strPoductContentName .= $strBr.$row1->product_content_name." ({$row1->language_name})";
                $i++;
            }
            $arrPoductContentName[$row->product_id] = $strPoductContentName;
        }
        $this->view->assign('arrPoductContentName', $arrPoductContentName);

        $this->view->assign('product', $products);
        $this->view->assign('numProduct', $numProduct);
        $this->view->assign('exp', $exp);
        $this->view->assign('pageIndex', $pageIndex);
        // Paginator
        /*$paginator = new Zend_Paginator(new Tomato_Core_Utility_PaginatorAdapter($articles, $numArticles));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);


        $this->view->assign('articles', $articles);
        $this->view->assign('numArticles', $numArticles);
        $this->view->assign('paginator', $paginator);
        $this->view->assign('paginatorOptions', array(
            'path'       => $this->view->url(array(), 'news_article_list'),
            'itemLink' => (null == $params) ? 'page-%d' : 'page-%d?q='.$params,
        ));*/
    }

    /**
     * Edit product
     * @return void
     **/
    public function editAction(){
        $this->view->addHelperPath(TOMATO_APP_DIR . DS . 'modules' . DS . 'upload' . DS . 'views' . DS . 'helpers', 'Upload_View_Helper_');

        $request = $this->getRequest();
        $id      = $request->getParam('product_id');

        /**
         * Get current user
        **/
        $user = Zend_Auth::getInstance()->getIdentity();

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Category model access to data
         **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
        * Enterprise user model access to data
        **/
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Get relationship info between user and enterprise
         **/
        $userAccount = $userAccountDao->getByUser($user->user_id);

        /**
         * Check enterprise exist
         * @return: die if enterprise_id not exist
        **/
        /*if(!isset($userAccount->enterprise_id) && !@$userAccount->enterprise_id){
            die('Not found enterprise for user');
        }*/

        /**
         * Get enterprise info for product currency
         **/
        if($userAccount){
            $enterprise = $enterpriseDao->getById($userAccount->enterprise_id);
            $this->view->assign('enterprise', $enterprise);
        }

        /**
         * Product model acess to data
         **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);

        /**
         * Product content model access to data
         **/
        $productContentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductContentDao();
        $productContentDao->setDbConnection($conn);

        /**
         * Get language system
         **/
        $lanuguages = $categoryDao->getLanguage();
        $this->view->assign('languages', $lanuguages);

        /**
         * Get category to tree view
         **/
        $categories = $categoryDao->getCategoryTree();
        $this->view->assign('categories', $categories);

        /**
         * Get current date
         **/
        $date = date('d/m/Y');
        $this->view->assign('date', $date);

        /**
         * Get product info to edit
         **/
        $product = $productDao->getProductById($id);
        $this->view->assign('product', $product);

        /**
        * Check permission all list enterprise
        */
        $isAllowed = true;
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            if(@$userAccount->enterprise_id){
                if($product->enterprise_id != @$userAccount->enterprise_id){
                    $isAllowed = false;
                    $this->view->assign('isAllowed', $isAllowed);
                    return;
                }
            }else{
                $isAllowed = false;
                $this->view->assign('isAllowed', $isAllowed);
                return;
            }
        }
        $this->view->assign('isAllowed', $isAllowed);

        /**
         * Get language content of product
         **/
        $product_content = $productContentDao->getProductContentByProductId($id);

        /**
         * Handle language content of product
         * $arrProductByLanguage: this is array store language content width index language_code
         **/
        $arrProductByLanguage = array();
        foreach ($product_content as $row){
            $arrProductByLanguage[$row->language_code] = $row;
        }
        $this->view->assign('arrProductByLanguage', $arrProductByLanguage);

        /**
        * Get string product id belong product bundel
        **/
        $edit_product_product_id_chain = $product->product_product_id_chain;

        /**
         * Handle string product id chain
         **/
        $str_explode_product_name = ',';
        if($edit_product_product_id_chain != ',')
        {
            $explode_product_product_id_chain = explode(',',substr(substr($edit_product_product_id_chain,1),0,-1));
            foreach ($explode_product_product_id_chain as $row_explode_product_product_id_chain)
            {
                $explode_productById = $productDao->getProductById($row_explode_product_product_id_chain);
                if(@$explode_productById->product_admin_name != '')
                {
                    $str_explode_product_name .= $explode_productById->product_admin_name.',';
                }
                else
                {
                    $str_explode_product_name = ',';
                }
            }
        }
        $this->view->assign('str_explode_product_name', $str_explode_product_name);

        if ($request->isPost()) {

            /**
             * String category choosed
             **/
            $arrCategoryId = $request->getPost('category_id');
            $strCategoryId = ",";
            foreach ($arrCategoryId as $row){
                $strCategoryId .= $row.',';
            }

            $id                         = $request->getParam('product_id');
            $product_admin_name         = $request->getPost('product_admin_name');
            $product_price              = $request->getPost('product_price');
            $product_price_currency     = isset($enterprise->currency)?$enterprise->currency:'USD';
            $product_status_of_delivery = $request->getPost('product_status_of_delivery');
            $product_quantity           = $request->getPost('product_quantity');
            $product_quantity_mode      = $request->getPost('product_quantity_mode');
            $product_status             = $request->getPost('product_status');
            $category_id                = $strCategoryId;
            $account_id                 = 1;//value to test
            $product_bundle             = $request->getPost('product_bundle');
            $product_shipping_price     = $request->getPost('product_shipping_price');
            $product_image              = $request->getPost('product_image');
            $enterprise_id              = ($userAccount)?$userAccount->enterprise_id:$product->enterprise_id;
            $product_product_id_chain   = ($request->getPost('product_product_id_chain'))?$request->getPost('product_product_id_chain'):',';
            $product_shipping_price_1   = $request->getPost('product_shipping_price_1');
            $product_shipping_price_2   = $request->getPost('product_shipping_price_2');


            $purifier = new HTMLPurifier();
            $product = new Shop_Models_Product(array(
                'product_admin_name'         => $purifier->purify($product_admin_name),
                'category_id'                => $category_id,
                'account_id'                 => $account_id,
                'product_price'              => $product_price,
                'product_price_currency'     => $product_price_currency,
                'product_status_of_delivery' => $product_status_of_delivery,
                'product_quantity'           => $product_quantity,
                'product_quantity_mode'      => $product_quantity_mode,
                'product_status'             => $product_status,
                'product_modified_date'      => date('Y-m-d H:i:s'),
                'product_bundle'             => $product_bundle,
                'product_product_id_chain'   => $product_product_id_chain,
                'product_shipping_price'     => $product_shipping_price,
                'product_image'              => $product_image,
                'enterprise_id'              => $enterprise_id,
                'product_shipping_price_1'   => $product_shipping_price_1,
                'product_shipping_price_2'   => $product_shipping_price_2,
            ));
            $productDao->edit($product, $id);
            $this->_helper->getHelper('FlashMessenger')->addMessage(
                $this->view->translator('product_edit_success')
            );

            $this->_redirect($this->view->serverUrl().$this->view->url(array('product_id' => $id), 'shop_product_edit'));
        }
    }

    /**
     * Delete product
     * @return void
     **/
    public function deleteAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $request = $this->getRequest();

        //get connection
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $productContentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductContentDao();
        $productContentDao->setDbConnection($conn);

        //get connection
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);

        //get connection product attribute
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $productAttributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductAttributeDao();
        $productAttributeDao->setDbConnection($conn);

        $result  = 'RESULT_ERROR';
        if ($request->isPost()) {
            $productId = $request->getPost('id');

            $productAttribute = $productAttributeDao->getAttributeTypeIdByProductId($productId);
            $strValueType = '';
            foreach ($productAttribute as $row){
                $strValueType .= $row->value_type_id_chain;
            }
            $strValueType = str_replace(',,',',',$strValueType);
            $arrValueType = explode(',', $strValueType);
            unset($arrValueType[0]);
            unset($arrValueType[count($arrValueType)]);
            /*foreach ($arrValueType as $row){
                $productAttributeDao->deleteValueContent($row);
                $productAttributeDao->deleteValueType($row);
            }*/
            $productAttributeDao->deleteProductAttribute($productId);//delete product attribute
            $productContentDao->delete($productId);//delete product content
            $productDao->delete($productId);//delete product
            $result = 'RESULT_OK';
        }
        $this->getResponse()->setBody($result);
    }

    /**
     * Save content of product
     * @return void
     **/
    public function saveContentAction(){

        //get connection product attribute
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $productAttributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductAttributeDao();
        $productAttributeDao->setDbConnection($conn);

        $request = $this->getRequest();
        //get connection
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $productContentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductContentDao();
        $productContentDao->setDbConnection($conn);

        if ($request->isPost()) {
            $product_content_id           = $request->getPost('product_content_id');
            $product_id                   = $request->getParam('product_id');
            $language_code                = $request->getPost('language_code');
            $product_content_name         = $request->getPost('product_content_name');
            $product_content_friendly_url = $request->getPost('product_content_friendly_url');
            $product_content_description  = $request->getPost('product_content_description');
            $auto_translate          	  = $request->getPost('auto_translate');
            $product_content_id_en        = $request->getPost('product_content_id_en');

            $purifier = new HTMLPurifier();
            $product_content = new Shop_Models_ProductContent(array(
                'product_id'                   => $product_id,
                'language_code'                => $language_code,
                'product_content_name'         => $purifier->purify($product_content_name),
                'product_content_friendly_url' => $purifier->purify($product_content_friendly_url),
                'product_content_description'  => $product_content_description
            ));

            if(!$product_content_id){
                $id = $productContentDao->addContent($product_content);                
            }else{
                $productContentDao->editContent($product_content,$product_content_id);
            }

            /**
            * Auto translator
            **/
            if(($auto_translate || !$product_content_id_en) && $language_code != 'en_US'){            	
                $product_content_name_en         = $this->translate($product_content_name);
                $product_content_friendly_url_en = Tomato_Utility_String::removeSign($product_content_name_en, '-', true);
                $product_content_description_en  = $purifier->purify($this->translate($product_content_description));
                $product_content_en = new Shop_Models_ProductContent(array(
                    'product_id'                   => $product_id,
                    'language_code'                => 'en_US',
                    'product_content_name'         => $purifier->purify($product_content_name_en),
                    'product_content_friendly_url' => $purifier->purify($product_content_friendly_url_en),
                    'product_content_description'  => $product_content_description_en
                ));
                if(!$product_content_id_en){
                    $productContentDao->addContent($product_content_en);
                }else{
                    $productContentDao->editContent($product_content_en,$product_content_id_en);
                }
            }            
            $this->_helper->getHelper('FlashMessenger')->addMessage($this->view->translator('product_add_success'));
            $this->_redirect($this->view->serverUrl().$this->view->url(array('product_id' => $product_id), 'shop_product_edit'));
        }
    }

    public function translate($text,$from = 'vi',$to = 'en') {
        $text = urlencode($text);
        $srcLang = urlencode( $from );
        $destLang = urlencode( $to );

        $trans = @file_get_contents( "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q={$text}&langpair={$srcLang}|{$destLang}");
		
        $translate = Zend_Json::decode($trans);
        $result = $translate['responseData']['translatedText'];
        return $result;
    }

    /**
     * Get attribute for product
     * @return void
    **/
    public function getAttributeAction(){
        $this->_helper->getHelper('layout')->disableLayout();

        $strCategory_id = $this->getRequest()->getParam('strCategory_id');
        $strAttributeTypeId = $this->getRequest()->getParam('strAttributeTypeId');
        $this->view->assign('strAttributeTypeId', $strAttributeTypeId);
        //get connection
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);

        $arrCategoryId = explode(',',$strCategory_id);
        unset($arrCategoryId[count($arrCategoryId)-1]);

        $result = array();
        foreach ($arrCategoryId as $row){
            $attribute = $productDao->getAttributeByCategoryId($row);
            foreach ($attribute as $row1) {
                $result[] = $row1;
            }
        }
        $arrResult = array();
        foreach ($result as $row){
            $arrResult[$row->attribute_type_id] = $row;
        }
        $this->view->assign('arrResult',$arrResult);
        /*$arrAttributeContent = array();
        foreach ($arrResult as $row){
            $attributeContent = $productDao->getAttributeContentByAttributeIdLanguage($row->attribute_type_id, $language_code);
            if(count($attributeContent)){
                $arrAttributeContent[] = $attributeContent;
            }
        }
        $this->view->assign('arrAttributeContent',$arrAttributeContent);*/
    }

    /**
     * List attribute add save attribute for product
     **/
    public function chooseAttributeAction(){
        $request = $this->getRequest();

        //get connection product attribute
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $productAttributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductAttributeDao();
        $productAttributeDao->setDbConnection($conn);

        //get connection category
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
         * Model Product access data
         **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);

        //get category
        $categories = $categoryDao->getCategoryTree();
        $this->view->assign('categories', $categories);

        $id         = $request->getParam('product_id');
        $this->view->assign('product_id',$id);

        $product = $productDao->getProductById($id);
        $this->view->assign('strCat', $product->category_id);

        $productAttribute = $productAttributeDao->getAttributeTypeIdByProductId($id);
        $strCategoryId = '';
        $strAttributeTypeId = ',';
        foreach ($productAttribute as $row){
            $strAttributeTypeId .= $row->attribute_type_id.',';
            $attributeType = $productAttributeDao->getAttributeTypeByAttributeTypeId($row->attribute_type_id);
            $strCategoryId .= $attributeType->category_id;
        }
        $this->view->assign('strCategoryId', $strCategoryId);
        $this->view->assign('strAttributeTypeId', $strAttributeTypeId);

        if ($request->isPost()) {
            $arrAttributeTypeId = $request->getPost('attribute_type_id');
            if(!$arrAttributeTypeId){
                $arrAttributeTypeId = array();
            }

            $arrAttributeTypeIdDB = array();
            foreach ($productAttribute as $row){
                $arrAttributeTypeIdDB[] = $row->attribute_type_id;
            }

            $arrListToDB = array_diff($arrAttributeTypeIdDB, $arrAttributeTypeId);
            $arrDBToList = array_diff($arrAttributeTypeId, $arrAttributeTypeIdDB);

            //delete
            if($arrListToDB){
                foreach ($arrListToDB as $row){
                    $productAttributeDao->delete($id, $row);
                }
            }
            //add
            if($arrDBToList){
                foreach ($arrDBToList as $row){
                    $product_attribute = new Shop_Models_ProductAttribute(array(
                        'product_id'        => $id,
                        'attribute_type_id' => $row
                    ));
                    $productAttributeDao->add($product_attribute);
                }
            }
            $this->_helper->getHelper('FlashMessenger')->addMessage($this->view->translator('product_choose_attribute_success'));
            $this->_redirect($this->view->serverUrl().$this->view->url(array('product_id' => $id), 'shop_product_choose_attribute'));
        }
    }

    /**
     * Save production duration
     * @return void
     **/
    public function productionDurationAction(){
        $request = $this->getRequest();
        //get database connection product
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);

        if ($request->isPost()) {
            $product_id = $request->getParam('product_id');
            $production_duration = $request->getPost('production_duration');

            $product = new Shop_Models_Product(array(
                'production_duration'        => $production_duration
            ));
            $productDao->updateProductionDuration($product, $product_id);
            $this->_helper->getHelper('FlashMessenger')->addMessage(
                $this->view->translator('product_edit_success')
            );
            $this->_redirect($this->view->serverUrl().$this->view->url(array('product_id' => $product_id), 'shop_product_edit'));
        }
    }

    /**
    * Duplicate product
    * @return void
    **/
    public function duplicateAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        //get database connection product
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);
        $productContentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductContentDao();
        $productContentDao->setDbConnection($conn);
        $productAttributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductAttributeDao();
        $productAttributeDao->setDbConnection($conn);

        //get category info to edit
        $request = $this->getRequest();
        $id         = $request->getParam('product_id');

        $product = $productDao->getProductById($id);
        $productContent = $productDao->getProductContentById($id);
        $productAttribute = $productAttributeDao->getAttributeTypeIdByProductId($id);

        if ($id > 0) {
            $product_admin_name         = 'Copy '.$product->product_admin_name;
            $product_price                   = $product->product_price;
            $product_price_currency        = $product->product_price_currency;
            $product_status_of_delivery = $product->product_status_of_delivery;
            $product_quantity               = $product->product_quantity;
            $product_quantity_mode         = $product->product_quantity_mode;
            $product_status               = $product->product_status;
            $category_id                   = $product->category_id;
            $account_id                   = $product->account_id;//value to test

            $production_duration        = $product->production_duration;
            $product_bundle                = $product->product_bundle;
            $product_product_id_chain    = $product->product_product_id_chain;
            $product_shipping_price        = $product->product_shipping_price;
            $product_image                = $product->product_image;

            $purifier = new HTMLPurifier();
            $product = new Shop_Models_Product(array(
                'product_admin_name'        => $purifier->purify($product_admin_name),
                'category_id'                   => $category_id,
                'account_id'                   => $account_id,
                'product_price'             => $product_price,
                'product_price_currency'    => $product_price_currency,
                'product_status_of_delivery'=> $product_status_of_delivery,
                'product_quantity'             => $product_quantity,
                'product_quantity_mode'     => $product_quantity_mode,
                'product_status'             => $product_status,
                'product_created_date'         => date('Y-m-d H:i:s'),
                'product_modified_date'     => date('Y-m-d H:i:s'),
                'production_duration'         => $production_duration,
                'product_bundle'             => $product_bundle,
                'product_product_id_chain'     => $product_product_id_chain,
                'product_shipping_price'    => $product_shipping_price,
                'product_image'                => $product_image
            ));

            $id = $productDao->add($product);

            foreach ($productContent as $rowProductContent){

                $product_id                     = $id;
                $language_code                     = $rowProductContent->language_code;
                $product_content_name             = $rowProductContent->product_content_name;
                $product_content_friendly_url    = $rowProductContent->product_content_friendly_url;
                $product_content_description     = $rowProductContent->product_content_description;

                $purifier = new HTMLPurifier();
                $product_content = new Shop_Models_ProductContent(array(
                    'product_id'                    => $product_id,
                    'language_code'                       => $language_code,
                    'product_content_name'               => $purifier->purify($product_content_name),
                    'product_content_friendly_url'    => $purifier->purify($product_content_friendly_url),
                    'product_content_description'    => $product_content_description
                ));

                $productContentDao->addContent($product_content);
            }

            foreach ($productAttribute as $rowProductAttribute){
                $product_attribute = new Shop_Models_ProductAttribute(array(
                    'product_id'        => $id,
                    'attribute_type_id' => $rowProductAttribute->attribute_type_id,
                    'value_type_id_chain' => $rowProductAttribute->value_type_id_chain
                ));

                $productAttributeDao->duplicate($product_attribute);
            }

            $result = 'RESULT_OK';
        }

        $this->getResponse()->setBody($result);
    }

    /**
    * Get product for choose item bundle
    * @return void
    **/
    public function bundleAction(){
        $this->_helper->getHelper('layout')->disableLayout();		
		$product_id  = $this->_request->getParam('product_id',null);
		try{
			/**
			 * Get current user
			**/
			$user = Zend_Auth::getInstance()->getIdentity();

			/**
			* Get connection to database
			**/
			$conn = Tomato_Db_Connection::factory()->getMasterConnection();

			/**
			* Enterprise model access to data
			**/
			$userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
			$userAccountDao->setDbConnection($conn);

			/**
			 * Get relationship info between user and enterprise
			 **/
			$userAccount = $userAccountDao->getByUser($user->user_id);

			/**
			 * Product model access to data
			 **/
			$productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
			$productDao->setDbConnection($conn);

			$proObj 	= $productDao->getProductById($product_id);					
			if($proObj == null)
			 throw new Exception('Product_id non exists');
			/**
			* Get product by enterprise id
			**/
			$exp = array(
				'product_status' => 1,
				'enterprise_id'  => $proObj->enterprise_id,
				'product_bundle' => 0 	
			);
			
			$product = array();
			$product = $productDao->find(null,null,$exp);
			// loai bo san pham dang xet ra khoi danh sach
			$arr = Array();
			if(count($product)){
				foreach($product as $pItem){
					$product_status_of_delivery = $pItem->product_status_of_delivery;
					$product_quantity           = $pItem->product_quantity;
					$product_quantity_mode		= $pItem->product_quantity_mode;
					// check het hang
					$existsP = true;
					if($product_status_of_delivery == "non_deliver_able")	$existsP = false;
					if($product_quantity_mode      == "amount" && $product_quantity<=0) $existsP = false;

					if($existsP && $pItem->product_id != $product_id)
						$arr[] = $pItem;
				}
			}
			$product = $arr;
			
			$value = $this->_request->getParam('value');
			$product_product_id_chain = $this->_request->getParam('product_product_id_chain');		
			$str_product_name = ',';
			$explode_product_product_id_chain = explode(',',substr(substr($product_product_id_chain,1),0,-1));
			$arrName = array();	
			foreach ($explode_product_product_id_chain as $row_product_product_id_chain)
			{			
				$productById = $productDao->getProductById($row_product_product_id_chain);
				if(isset($productById->product_admin_name) && $productById->product_admin_name != null){
					$str_product_name .= $productById->product_admin_name.',';
					$arrName[$row_product_product_id_chain]["product_name"]  = $productById->product_admin_name;
					$arrName[$row_product_product_id_chain]["count"]  		 = isset($arrName[$row_product_product_id_chain]["count"])? ($arrName[$row_product_product_id_chain]["count"] + 1): 1;
					$arrName[$row_product_product_id_chain]["id"]	= $productById->product_id;
				}
				else{
					$str_product_name = ',';
				}			
			}
			$this->view->assign('product', $product);
			$this->view->assign('product_product_id_chain', $product_product_id_chain);
			$this->view->assign('str_product_name', $str_product_name);
			$this->view->assign('arrName', $arrName);
		}catch(Exception $ex){
			$this->view->assign('product',null);
		}
    }

    /*===============================Front-end Action=================================*/

    /**
     * Get category to view drop down menu
     * @return void
     **/
    public function categoryAction(){
        $request    = $this->getRequest();
        $categoryId = $request->getParam('category_id');
        $lang = $request->getParam('lang');
        $count = 5;

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
        * Product models access to data
        **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);

        /**
         * Set current language for model
         **/
        $productDao->setLang($lang);

        /**
         * Category access to data
         **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
         * Set current language for model
         **/
        $categoryDao->setLang($lang);

        /**
        *
        **/
        if($categoryId){
            $categoriesLevel = $categoryDao->getDirSubCategory($categoryId);
            $this->view->assign('categories', $categoriesLevel);

            $category = $categoryDao->getCategoryById($categoryId);
            $this->view->assign('category', $category);
        }else{
            $categories = $categoryDao->getFTree();
            $categoriesLevel = array();
            foreach ($categories as $row){
                if($row->depth == 0){
                    $categoriesLevel[] = $row;
                }
            }
        }
        if(count($categoriesLevel) > 0){
            $arrProduct = array();
            $arrDirSubs = array();
            foreach($categoriesLevel as $row){
                $dirSubs = $categoryDao->getDirSubCategory($row->category_id);

                $arrProducSubs = array();
                if(count($dirSubs)){
                    foreach($dirSubs as $dirSub){
                        $subInfo = $categoryDao->getCategoryById($dirSub->category_id);
                        $arrProductSub = array();

                        $exp = array(
                            'category_id' => $dirSub->category_id,
							'frontend_active'=>1,
							'deleted'	  => 0
                        );
                        $products = $productDao->find(0, $count, $exp);
                        foreach($products as $pRow){
                            $arrProductSub[$pRow->product_id] = $pRow;
                        }

                        $allSubs = $categoryDao->getSubCategory($subInfo);
                        if($allSubs){
                            foreach($allSubs as $allSub){
                                $exp = array(
                                    'category_id' => $allSub->category_id,
									'frontend_active'=>1,
									'deleted'	  => 0
                                );
                                $products = $productDao->find(0, $count, $exp);
                                foreach($products as $pRow){
                                    $arrProductSub[$pRow->product_id] = $pRow;
                                }
                            }
                        }
                        $arrProducSubs[$dirSub->category_id] = $arrProductSub;
                    }
                }else{
                    $exp = array(
                        'category_id' => $row->category_id,
						'frontend_active'=>1,
						'deleted'	  => 0						
                    );
                    $products = $productDao->find(0, 4, $exp);
                    foreach($products as $pRow){
                        $arrProductSubs[$pRow->product_id] = $pRow;
                    }
                    $arrProducSubs[$row->category_id] = $arrProductSubs;
                }
                $arrDirSubs[$row->category_id] = $dirSubs;
                $arrProduct[$row->category_id] = $arrProducSubs;
            }
            $this->view->assign('categories', $categoriesLevel);
            $this->view->assign('subCategories', $arrDirSubs);
            $this->view->assign('products', $arrProduct);
        }else{
            $category = $categoryDao->getCategoryById($categoryId);
            $exp = array(
                'category_id' => $categoryId,
				'frontend_active'=>1,
				'deleted'	  => 0				
            );
            $products = $productDao->find(0, $count, $exp);
            $this->view->assign('category', $category);
            $this->view->assign('products', $products);
        }
    }

    /**
     * Get product info detail follow langauge
     * @return void
     **/
    public function detailAction(){    	
        $request = $this->getRequest();

        $enterprise_id = null;
        $params = $request->getParams();
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $user = $auth->getIdentity();
            if($user->enterprise){
                $enterprise_id = $user->enterprise->id;
            }
        }
        if(isset($params['enterprise_id'])){
            $enterprise_id = $params['enterprise_id'];
        }

        $product_id = $request->getParam('product_id');
        $lang = $request->getParam('lang');
        $this->view->assign('lang', $lang);

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Product model access to data
         **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setLang($lang);
        $productDao->setDbConnection($conn);

        /**
         * Category models access to data
         */
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);
        $categoryDao->setLang($lang);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
        * Attribute model access to data
        **/
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);
        $attributeDao->setLang($lang);

        /**
        * Value model access to data
        **/
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);
        $valueDao->setLang($lang);

        /**
        * Cart models access to data
        **/
        $cartDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shoppingcart')->getCartDao();
        $cartDao->setDbConnection($conn);
        $cartDao->setLang($lang);

        /**
         * Get current enterprise
        **/
        $objEnterprise = $enterpriseDao->getById($enterprise_id);
        $found = true;
        if (null == $objEnterprise) {
            $found = false;
        }
        $this->view->assign('found', $found);
        $this->view->assign('enterprise', $objEnterprise);

        /**
         * Get product info follow language
         **/

         $product = $productDao->getProductById($product_id, $lang);
		 /*
			if product status is hidden redirect to main products page
		 */
		 if($product->product_status < 1){ //products
			$this->_redirect($this->view->serverUrl().$this->view->url(array(), 'shop_product_all_products'));
		}
         $this->view->assign('product', $product);

         /**
          * Update view count for product
         **/
         if($product){
            $viewCount = $productDao->getMarketData($product_id);
            $data = new Shop_Models_Product(array(
                    'product_id' => $product_id,
                    'category_id' => substr(substr($product->category_id,1),0,-1),
                    'view_count' => 1
            ));
            if(!$viewCount){
                /**Insert new row*/
                $productDao->addMarketData($data);
            }else{
                //die('u');
                /**Update row*/
                $productDao->updateMarketData($data);
            }
         }

        /**
        * Check exist cart
        **/
        $pEndcode = $request->getParam('p');
        $arrDecode = rawurldecode(base64_decode($pEndcode));
        $pDecode = Zend_Json::decode($arrDecode);
        $cart_id = $pDecode[0];
        $arrAttValue = array();
        if(null != $cart_id && is_numeric($cart_id)){
            $cart_detail = $cartDao->getCDById($cart_id);
            if($cart_detail){
                $arrAttValue = Zend_Json::decode($cart_detail->product_attribute_value_id_chain);
            }
            $this->view->assign('cart_detail', $cart_detail);
        }
        $this->view->assign('arrAttValue', $arrAttValue);

         /**
          * Get category of product
         **/
         $category_id = substr(substr($product->category_id,1),0,-1);
         $category = $categoryDao->getById($category_id);
         $this->view->assign('objCategory', $category);

        /**
        * Get attribute of product
        **/
        $attributes = $attributeDao->getAttOfPro($product_id);
        $this->view->assign('attributes', $attributes);

        /**
         * Build array value of attribute
        **/
        $arrValues = array();
        foreach($attributes as $attribute){
            $arrValues[$attribute->attribute_type_id] = $valueDao->values($attribute->value_type_id_chain);
        }
        $this->view->assign('values', $arrValues);

        $arrValuesVN = array();
        foreach($attributes as $attribute){
            $valueDao->setLang('vi_VN');
            $arrValuesVN[$attribute->attribute_type_id] = $valueDao->values($attribute->value_type_id_chain);
        }
        $this->view->assign('valuesVN', $arrValuesVN);

        /**
         * Related product
        **/
        $perPage    = 10;
        $offset     = 0;
        $purifier     = new HTMLPurifier();

        /**
         * Build product search expression
         **/
        $exp    = array(
						'frontend_active'=>1,
						'deleted'	  => 0
				  );				  
        $exp['enterprise_id'] = $purifier->purify($enterprise_id);
        $exp['product_status'] = 1;
        $exp['category_id'] = $category_id;

        /**
        * Get list product and count all product to paginator
        * $offset: position start
        * $perPage: item pager
        * $exp: condition
        **/
        $products = $productDao->find($offset, $perPage, $exp);

        /**
         * Related product
        **/
        $relatedProducts = array();
        foreach($products as $subProduct){
            if($subProduct->product_id != $product->product_id){
                $relatedProducts[] = $subProduct;
            }
        }
        $this->view->assign('relatedProducts', $relatedProducts);

        /**
          * Get category of product
         **/
        $arrPC = array();
        foreach($relatedProducts as $product){
            $category_id = substr(substr($product->category_id,1),0,-1);
            $objCategory = $categoryDao->getById($category_id);
            $arrPC[$product->product_id] = $objCategory;
        }
        $this->view->assign('arrPC', $arrPC);        
        
        /**
         * Check current number item existed in cart
         */
        $cart_id = $_COOKIE['cart_cookie'];        
        
        $sumQty = $cartDao->sumQty($cart_id, $product_id);
        $qtyItems = ($sumQty)?$sumQty:0;
        
        $this->view->assign('qtyItems', $qtyItems);
    }

    /**
    * Get products of enterprise
    * @return void
    **/
    public function productsAction(){

        $request = $this->getRequest();
        $lang = $request->getParam('lang');

        $enterprise_id = null;
        $params = $request->getParams();
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $user = $auth->getIdentity();
            if($user->enterprise){
                $enterprise_id = $user->enterprise->id;
            }
        }
        if(isset($params['enterprise_id'])){
            $enterprise_id = $params['enterprise_id'];
        }

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Product model access to data
         **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);
        $productDao->setLang($lang);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Category models access to data
         */
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);
        $categoryDao->setLang($lang);
        
        /**
        * Cart models access to data
        **/
        $cartDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shoppingcart')->getCartDao();
        $cartDao->setDbConnection($conn);
        $cartDao->setLang($lang);

        /**
         * Get category of enterprise
        **/
        $categories = $productDao->catOfEnt($enterprise_id);

        /**
        * Count item in category
        **/
        $arrCategories = array();
		$arrToCount    = array();
        foreach($categories as $category){
            $arrCategories[$category->category_id] = $category;
            $arrToCount[] = $category->category_id;
        }
        $arrCounted = array_count_values($arrToCount);
        $this->view->assign('categories', $arrCategories);
        $this->view->assign('arrCounted', $arrCounted);

        /**
         * Get current enterprise
        **/
        $objEnterprise = $enterpriseDao->getById($enterprise_id);
        $found = true;
        if (null == $objEnterprise) {
            $found = false;
        }
        $this->view->assign('found', $found);
        $this->view->assign('enterprise', $objEnterprise);

        $pageIndex  = $this->_request->getParam('pageIndex', 1);
        $perPage    = 20;
        $offset     = ($pageIndex - 1) * $perPage;
        $purifier     = new HTMLPurifier();

        /**
         * Build product search expression
         **/
        $params = null;
        $exp    = array(
						'frontend_active'=>1,
						'deleted'	  => 0		
				  );

        $exp['enterprise_id'] = $purifier->purify($enterprise_id);
        $exp['product_status'] = 1;

        $category_id = $request->getParam('cat');
        $this->view->assign('category_id', $category_id);
        $category = null;
        if(null != $category_id){
            $exp['category_id'] = $category_id;
            $category = $categoryDao->getById($category_id);
        }
        $this->view->assign('objCategory', $category);

        /**
        * Get list product and count all product to paginator
        * $offset: position start
        * $perPage: item pager
        * $exp: condition
        **/
        $products = $productDao->find($offset, $perPage, $exp);
        $numProduct = $productDao->count($exp);

        $this->view->assign('products', $products);
        $this->view->assign('count', $numProduct);

        /**
          * Get category of product
         **/
        $arrPC = array();
        $arrQtyItems = array();
        $cart_id = $_COOKIE['cart_cookie'];
        
        foreach($products as $product){
            $category_id = substr(substr($product->category_id,1),0,-1);
            $objCategory = $categoryDao->getById($category_id);
            $arrPC[$product->product_id] = $objCategory;            
            
            /**
	         * Check current number item existed in cart
	         */            
            $sumQty = $cartDao->sumQty($cart_id, $product->product_id);
            $qtyItems = ($sumQty)?$sumQty:0;	        
	        $arrQtyItems[$product->product_id] = $qtyItems;
        }
        $this->view->assign('arrPC', $arrPC);
        $this->view->assign('arrQtyItems', $arrQtyItems);
    }

    public function allProductsAction(){
		$conn = Tomato_Db_Connection::factory()->getMasterConnection();		
		
        $category_id = 0;
        $serUrl = $this->view->APP_STATIC_SERVER. "/images/advertise/products";

        /**
        * Get image advertise
        **/
        /**Image 1*/
        $file1 = $serUrl."/".$category_id."_sanpham1.jpg";
        $path1 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file1);
        $urlImage1 = is_file($path1)?$file1:null;

        /**Image 2*/
        $file2 = $serUrl."/".$category_id."_sanpham2.jpg";
        $path2 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file2);
        $urlImage2 = is_file($path2)?$file2:null;

        /**Image 3*/
        $file3 = $serUrl."/".$category_id."_sanpham3.jpg";
        $path3 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file3);
        $urlImage3 = is_file($path3)?$file3:null;

        /**Image 4*/
        $file4 = $serUrl."/".$category_id."_sanpham4.jpg";
        $path4 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file4);
        $urlImage4 = is_file($path4)?$file4:null;

        /**Image 5*/
        $file5 = $serUrl."/".$category_id."_sanpham5.jpg";
        $path5 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file5);
        $urlImage5 = is_file($path5)?$file5:null;

        $arrImage = array(
            1 => $urlImage1,
            2 => $urlImage2,
            3 => $urlImage3,
            4 => $urlImage4,
            5 => $urlImage5,
        );
        $this->view->assign('arrImage', $arrImage);

        /**
         * Get link advertise
        **/
        $file = $serUrl."/".$category_id."_link.txt";
        $path = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file);
        $arrLink = null;
        if(is_file($path)){
            $content = file_get_contents($path);
            $arrLink = Zend_Json::decode($content);
        }
        $this->view->assign('arrLink', $arrLink);
	}

    public function allCategoriesAction(){
        $request     = $this->getRequest();
        $category_id = $request->getParam('cat');
        $lang        = $request->getParam('lang');

        $serUrl = $this->view->APP_STATIC_SERVER. "/images/advertise/products";

        /**
        * Get image advertise
        **/
        /**Image 1*/
        $file1 = $serUrl."/".$category_id."_sanpham1.jpg";
        $path1 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file1);
        $urlImage1 = is_file($path1)?$file1:null;

        /**Image 2*/
        $file2 = $serUrl."/".$category_id."_sanpham2.jpg";
        $path2 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file2);
        $urlImage2 = is_file($path2)?$file2:null;

        /**Image 3*/
        $file3 = $serUrl."/".$category_id."_sanpham3.jpg";
        $path3 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file3);
        $urlImage3 = is_file($path3)?$file3:null;

        /**Image 4*/
        $file4 = $serUrl."/".$category_id."_sanpham4.jpg";
        $path4 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file4);
        $urlImage4 = is_file($path4)?$file4:null;

        /**Image 5*/
        $file5 = $serUrl."/".$category_id."_sanpham5.jpg";
        $path5 = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file5);
        $urlImage5 = is_file($path5)?$file5:null;

        $arrImage = array(
            1 => $urlImage1,
            2 => $urlImage2,
            3 => $urlImage3,
            4 => $urlImage4,
            5 => $urlImage5,
        );
        $this->view->assign('arrImage', $arrImage);

        /**
         * Get link advertise
        **/
        $file = $serUrl."/".$category_id."_link.txt";
        $path = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file);
        if(is_file($path)){
            $content = file_get_contents($path);
            $arrLink = Zend_Json::decode($content);
        }
        $this->view->assign('arrLink', $arrLink);

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Product model access to data
         **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);
        $productDao->setLang($lang);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Category models access to data
         */
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);
        $categoryDao->setLang($lang);

        $category = $categoryDao->getCategoryById($category_id, 1);
        $this->view->assign('category', $category);
        if($category->category_parent_id > 0){
            $arrRoute = array(
                'category_id'  => $category->category_id,
                'slug' => ($category->slug)?$category->slug:Tomato_Utility_String::removeSign($category->category_admin_name, '-', true),
            );
            $this->_redirect($this->view->serverUrl().$this->view->url($arrRoute, 'shop_product_sub_categories'));
        }
    }

    public function subCategoriesAction(){
        $request     = $this->getRequest();
        $category_id = $request->getParam('category_id');
        $lang        = $request->getParam('lang');

        $pageIndex  = $this->_request->getParam('pageIndex', 1);
        $perPage    = 20;
        $offset     = ($pageIndex - 1) * $perPage;
        $params     = null;
        $purifier     = new HTMLPurifier();

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Product model access to data
         **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);
        $productDao->setLang($lang);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Category models access to data
         */
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);
        $categoryDao->setLang($lang);

        /**
        * Get current category
        **/
        $category = $categoryDao->getCategoryById($category_id, 1);
        $this->view->assign('category', $category);

        /**
        * Get direct sub category
        **/
        $dirSubCat = $categoryDao->getDirSubCategory($category_id);
        $this->view->assign('dirSubCat', $dirSubCat);

        /**
        * Count item in sub category
        **/
        $arrNumItem = array();
		$exp = array(
					'frontend_active'=>1,
					'deleted'	  => 0		
				);
        foreach($dirSubCat as $dircat){
            $subCategories = $categoryDao->getAllSub($dircat->category_id);
            $strCat = ',';
            foreach($subCategories as $subCategory){
                $strCat .= $subCategory->category_id.',';
            }
            $exp['strcat_id']      = $strCat;
            $exp['product_status'] = 1;
            $numProduct = $productDao->frontCount($exp);

            $arrNumItem[$dircat->category_id] = $numProduct;
        }
        $this->view->assign('arrNumItem', $arrNumItem);

        /**
        * get product of current category
        **/
        $exp['category_id'] = $category_id;
        $products = $productDao->find($offset,$perPage,$exp);
        $numProduct = $productDao->count($exp);

        // Paginator
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($products, $numProduct));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

        $this->view->assign('products', $products);
        $this->view->assign('numProduct', $numProduct);
        $this->view->assign('exp', $exp);
        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('paginator', $paginator);

        $arrRoute = array(
            'category_id' => $category->category_id,
            'slug' => ($category->slug)?$category->slug:Tomato_Utility_String::removeSign($category->category_admin_name, '-', true),
        );
        $this->view->assign('paginatorOptions', array(
            'path'       => $this->view->url($arrRoute, 'shop_product_sub_categories'),
            'itemLink' => (null == $params) ? 'page-%d' : 'page-%d?q='.$params,
        ));

        /**
        * Get category of product
        * Enterprise of product
        **/
        $arrPC = array();
        $arrPE = array();
        foreach($products as $product){
            $category_id = substr(substr($product->category_id,1),0,-1);
            $objCategory = $categoryDao->getById($category_id);
            $arrPC[$product->product_id] = $objCategory;

            $objEnterprise = $enterpriseDao->getById($product->enterprise_id);
            $arrPE[$product->product_id] = $objEnterprise;
        }
        $this->view->assign('arrPC', $arrPC);
        $this->view->assign('arrPE', $arrPE);
    }

    public function searchAction(){
        $request = $this->getRequest();
        $lang = $request->getParam('lang');

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Product model access to data
         **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);
        $productDao->setLang($lang);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Category models access to data
         */
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);
        $categoryDao->setLang($lang);

        $pageIndex  = $this->_request->getParam('pageIndex', 1);
        $perPage    = 20;
        $offset     = ($pageIndex - 1) * $perPage;
        $purifier     = new HTMLPurifier();

        /**
         * Build product search expression
         **/
        $params = null;
        $exp    = array(
						'frontend_active'=>1,
						'deleted'	  => 0		
					);
        $exp['product_status'] = 1;

        if ($request->isPost()) {
            $keyword = $request->getPost('keyword');
            $category_id = $request->getPost('category_id');

            if(trim($keyword) != null){
                $exp['keyword'] = $keyword;
            }
            if($category_id != 'all'){
                $exp['category_id'] = $category_id;
            }
            $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));

            $this->_redirect($this->view->serverUrl().$this->view->url(array(), 'shop_product_search').'/?q='.$params);
        }
        else {
            $params = $request->getParam('q');
            if (null != $params) {
                $exp = rawurldecode(base64_decode($params));
                $exp = Zend_Json::decode($exp);
            } else {
                $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
            }
        }

        $key = false;
        if(isset($exp['keyword'])){
            $key = true;
			
            $products = $productDao->search($offset,$perPage,$exp);
            $numProduct = $productDao->searchcount($exp);

            // Paginator
            $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($products, $numProduct));
            $paginator->setCurrentPageNumber($pageIndex);
            $paginator->setItemCountPerPage($perPage);

            $this->view->assign('products', $products);
            $this->view->assign('numProduct', $numProduct);
            $this->view->assign('exp', $exp);
            $this->view->assign('pageIndex', $pageIndex);
            $this->view->assign('paginator', $paginator);

            $this->view->assign('paginatorOptions', array(
                'path'       => $this->view->url(array(), 'shop_product_search'),
                'itemLink' => (null == $params) ? 'page-%d' : 'page-%d?q='.$params,
            ));

            /**
            * Get category of product
            * Enterprise of product
            **/
            $arrPC = array();
            $arrPE = array();
            $strPId = ',';
            foreach($products as $product){
                $category_id = substr(substr($product->category_id,1),0,-1);
                $objCategory = $categoryDao->getById($category_id);
                $arrPC[$product->product_id] = $objCategory;

                $objEnterprise = $enterpriseDao->getById($product->enterprise_id);
                $arrPE[$product->product_id] = $objEnterprise;

                $strPId .= $product->product_id.',';
            }
            $this->view->assign('arrPC', $arrPC);
            $this->view->assign('arrPE', $arrPE);
            $this->view->assign('strPId', $strPId);
        }
        $this->view->assign('key', $key);
    }

    /**
    * search related product
    * @return void
    **/
    public function searchAjaxAction(){
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();
        $lang = $request->getParam('lang');

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Product model access to data
         **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);
        $productDao->setLang($lang);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Category models access to data
         */
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);
        $categoryDao->setLang($lang);

        $pageIndex  = $this->_request->getParam('pageIndex', 1);
        $perPage    = 20;
        $offset     = ($pageIndex - 1) * $perPage;
        $purifier     = new HTMLPurifier();

        /**
         * Build product search expression
         **/
        $params = null;
        $exp    = array(
			"frontend_active" => 1,
			"deleted"		  => 0
		);
        $exp['product_status'] = 1;

        if ($request->isPost()) {
            $keyword = $request->getPost('keyword');
            $category_id = $request->getPost('category_id');
            $strPId = $request->getPost('strPId');

            $exp['keyword'] = $keyword;
            $exp['strPId'] = $strPId;
            if($category_id != 'all'){
                $exp['category_id'] = $category_id;
            }

            $products = $productDao->search($offset,$perPage,$exp,true);
            $numProduct = $productDao->searchcount($exp,true);

            // Paginator
            $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($products, $numProduct));
            $paginator->setCurrentPageNumber($pageIndex);
            $paginator->setItemCountPerPage($perPage);

            $this->view->assign('products', $products);
            $this->view->assign('numProduct', $numProduct);
            $this->view->assign('exp', $exp);
            $this->view->assign('pageIndex', $pageIndex);
            $this->view->assign('paginator', $paginator);

            $this->view->assign('paginatorOptions', array(
                'path'       => $this->view->url(array(), 'shop_product_search_ajax'),
                'itemLink' => (null == $params) ? 'page-%d' : 'page-%d?q='.$params,
            ));

            /**
            * Get category of product
            * Enterprise of product
            **/
            $arrPC = array();
            $arrPE = array();
            foreach($products as $product){
                $category_id = substr(substr($product->category_id,1),0,-1);
                $objCategory = $categoryDao->getById($category_id);
                $arrPC[$product->product_id] = $objCategory;

                $objEnterprise = $enterpriseDao->getById($product->enterprise_id);
                $arrPE[$product->product_id] = $objEnterprise;
            }
            $this->view->assign('arrPC', $arrPC);
            $this->view->assign('arrPE', $arrPE);
        }
    }

    /**
     * Search product with multi option
     * @return void
    **/
    public function searchAdvancedAction(){

        $request = $this->getRequest();
        $lang = $request->getParam('lang');

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Product model access to data
         **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);
        $productDao->setLang($lang);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Category models access to data
         */
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);
        $categoryDao->setLang($lang);

        /**
        * Attribute model access to data
        **/
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);
        $attributeDao->setLang($lang);

        /**
        * Value model access to data
        **/
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);
        $valueDao->setLang($lang);

        /**
        * Get category for selectbox
        **/
        $categories = $categoryDao->getFTree();
        $this->view->assign('objCategories', $categories);

        /**
         * Attribute for selectbox
        **/
        $attributes= $attributeDao->getAllAtt();
        $this->view->assign('attributes', $attributes);

        $pageIndex  = $this->_request->getParam('pageIndex', 1);
        $perPage    = 20;
        $offset     = ($pageIndex - 1) * $perPage;
        $purifier     = new HTMLPurifier();

        /**
         * Build product search expression
         **/
        $params = null;
        $exp    = array(
							'frontend_active'=>1,
							'deleted'	  => 0
				);
        $exp['product_status'] = 1;

        if ($request->isPost()) {
            $keyword = $request->getPost('keyword');
            $attribute_id = $request->getPost('attribute_id');
            $key_value = $request->getPost('value');
            $category_id = $request->getPost('category_id');

            $exp['keyword'] = $keyword;
            if($category_id != 'all'){
                $exp['category_id'] = $category_id;
            }
            if($attribute_id != 'all'){
                $exp['attribute_id'] = $attribute_id;
            }
            if(trim($key_value) != null){
                $exp['key_value'] = $key_value;
            }
            $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));

            $this->_redirect($this->view->serverUrl().$this->view->url(array(), 'shop_product_search_advanced').'/?q='.$params);

        } else {
            $params = $request->getParam('q');
            if (null != $params) {
                $exp = rawurldecode(base64_decode($params));
                $exp = Zend_Json::decode($exp);
            } else {
                $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
            }
        }

        $flag = false;
        $key = false;
        if($request->getParam('q') != null){
            $flag = true;

            if(trim($exp['keyword']) != null){
                $key = true;
                if(isset($exp['key_value'])){
                    $values = $valueDao->search($exp['key_value']);
                    $strValueId = ',';
                    foreach($values as $value){
                        $strValueId .= $value->value_type_id.',|,';
                    }
                    $strValueId = substr($strValueId,0,-2);
                    $exp['value'] = $strValueId;
                }

                $products = $productDao->advanced($offset,$perPage,$exp);
                $numProduct = $productDao->advancedcount($exp);

                // Paginator
                $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($products, $numProduct));
                $paginator->setCurrentPageNumber($pageIndex);
                $paginator->setItemCountPerPage($perPage);

                $this->view->assign('products', $products);
                $this->view->assign('numProduct', $numProduct);
                $this->view->assign('exp', $exp);
                $this->view->assign('pageIndex', $pageIndex);
                $this->view->assign('paginator', $paginator);

                $this->view->assign('paginatorOptions', array(
                    'path'       => $this->view->url(array(), 'shop_product_search_advanced'),
                    'itemLink' => (null == $params) ? 'page-%d' : 'page-%d?q='.$params,
                ));

                /**
                * Get category of product
                * Enterprise of product
                **/
                $arrPC = array();
                $arrPE = array();
                $strPId = ',';
                foreach($products as $product){
                    $category_id = substr(substr($product->category_id,1),0,-1);
                    $objCategory = $categoryDao->getById($category_id);
                    $arrPC[$product->product_id] = $objCategory;

                    $objEnterprise = $enterpriseDao->getById($product->enterprise_id);
                    $arrPE[$product->product_id] = $objEnterprise;

                    $strPId .= $product->product_id.',';
                }
                $this->view->assign('arrPC', $arrPC);
                $this->view->assign('arrPE', $arrPE);
                $this->view->assign('strPId', $strPId);
            }
        }
        $this->view->assign('flag', $flag);
        $this->view->assign('key', $key);
    }

    public function resultAjaxAction(){
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();
        $lang = $request->getParam('lang');

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Product model access to data
         **/
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);
        $productDao->setLang($lang);

        /**
        * Enterprise model access to data
        **/
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Category models access to data
         */
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);
        $categoryDao->setLang($lang);

        /**
        * Attribute model access to data
        **/
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);
        $attributeDao->setLang($lang);

        /**
        * Value model access to data
        **/
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);
        $valueDao->setLang($lang);

        $pageIndex  = $this->_request->getParam('pageIndex', 1);
        $perPage    = 20;
        $offset     = ($pageIndex - 1) * $perPage;
        $purifier     = new HTMLPurifier();

        /**
         * Build product search expression
         **/
        $params = null;
        $exp    = array(
						'frontend_active'=>1,
						'deleted'	  => 0		
				  );
        $exp['product_status'] = 1;

        if ($request->isPost()) {
            $keyword = $request->getPost('keyword');
            $attribute_id = $request->getPost('attribute_id');
            $key_value = $request->getPost('value');
            $category_id = $request->getPost('category_id');
            $strPId = $request->getPost('strPId');

            $exp['keyword'] = $keyword;
            $exp['strPId'] = $strPId;
            if($category_id != 'all'){
                $exp['category_id'] = $category_id;
            }
            if($attribute_id != 'all'){
                $exp['attribute_id'] = $attribute_id;
            }
            if(trim($key_value) != null){
                $exp['key_value'] = $key_value;
            }

            if(isset($exp['key_value'])){
                $values = $valueDao->search($exp['key_value']);
                $strValueId = ',';
                foreach($values as $value){
                    $strValueId .= $value->value_type_id.',|,';
                }
                $strValueId = substr($strValueId,0,-2);
                $exp['value'] = $strValueId;
            }

            $products = $productDao->advanced($offset,$perPage,$exp,true);
            $numProduct = $productDao->advancedcount($exp,true);

            // Paginator
            $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($products, $numProduct));
            $paginator->setCurrentPageNumber($pageIndex);
            $paginator->setItemCountPerPage($perPage);

            $this->view->assign('products', $products);
            $this->view->assign('numProduct', $numProduct);
            $this->view->assign('exp', $exp);
            $this->view->assign('pageIndex', $pageIndex);
            $this->view->assign('paginator', $paginator);

            $this->view->assign('paginatorOptions', array(
                'path'       => $this->view->url(array(), 'shop_product_search_advanced_ajax'),
                'itemLink' => (null == $params) ? 'page-%d' : 'page-%d?q='.$params,
            ));

            /**
            * Get category of product
            * Enterprise of product
            **/
            $arrPC = array();
            $arrPE = array();
            foreach($products as $product){
                $category_id = substr(substr($product->category_id,1),0,-1);
                $objCategory = $categoryDao->getById($category_id);
                $arrPC[$product->product_id] = $objCategory;

                $objEnterprise = $enterpriseDao->getById($product->enterprise_id);
                $arrPE[$product->product_id] = $objEnterprise;
            }
            $this->view->assign('arrPC', $arrPC);
            $this->view->assign('arrPE', $arrPE);
        }
    }
}